package com.hmj.hmjaiagent.agent.model;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.internal.StringUtil;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.UserMessage;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;

@Data
@Slf4j
public abstract class BaseAgent {
    private String agentName;

    private String systemPrompt;
    private String nextStepPrompt;

    private AgentState state = AgentState.IDLE;

    private int maxSteps = 10;
    private int currentStep = 0;

    private ChatClient chatClient;

    private List<Message> messages = new ArrayList<Message>();

    public String run(String userPrompt){
        if (this.state != AgentState.IDLE) {
            throw new IllegalStateException("Agent is not in IDLE state");
        }
        if (StringUtil.isBlank(userPrompt)) {
            throw new IllegalArgumentException("userPrompt is blank");
        }

        this.state = AgentState.RUNNING;
        this.messages.add(new UserMessage(userPrompt));

        List<String > results = new ArrayList<>();

        try {
            for (int i = 0; i < this.maxSteps && this.state != AgentState.FINISHED; i++) {
                this.currentStep = i + 1;
                log.info("Current step: " + this.currentStep + "/" + this.maxSteps);

                String stepResult = step(userPrompt);
                String result = "Step number: " + this.currentStep + ":" + stepResult ;
                results.add(result);
            }
            if (currentStep >= this.maxSteps){
                state = AgentState.FINISHED;
                results.add("Finished, reached max steps: " + this.maxSteps);
            }

            return String.join("\n", results);
        } catch (Exception e) {
            this.state = AgentState.ERROR;
            return "Error: " + e.getMessage();
        } finally {
            this.clean();
        }
    }

    /**
     * 运行代理（流式输出）
     *
     * @param userPrompt 用户提示词
     * @return SseEmitter实例
     */
    public SseEmitter runStream(String userPrompt) {
        // 创建SseEmitter，设置较长的超时时间
        SseEmitter emitter = new SseEmitter(300000L); // 5分钟超时

        // 使用线程异步处理，避免阻塞主线程
        CompletableFuture.runAsync(() -> {
            try {
                if (this.state != AgentState.IDLE) {
                    emitter.send("错误：无法从状态运行代理: " + this.state);
                    emitter.complete();
                    return;
                }
                if (StringUtil.isBlank(userPrompt)) {
                    emitter.send("错误：不能使用空提示词运行代理");
                    emitter.complete();
                    return;
                }

                // 更改状态
                state = AgentState.RUNNING;
                // 记录消息上下文
                messages.add(new UserMessage(userPrompt));

                try {
                    for (int i = 0; i < maxSteps && state != AgentState.FINISHED; i++) {
                        int stepNumber = i + 1;
                        currentStep = stepNumber;
                        log.info("Executing step " + stepNumber + "/" + maxSteps);

                        // 单步执行
                        String stepResult = step(userPrompt);
                        String result = "Step " + stepNumber + ": " + stepResult;

                        // 发送每一步的结果
                        emitter.send(result);
                    }
                    // 检查是否超出步骤限制
                    if (currentStep >= maxSteps) {
                        state = AgentState.FINISHED;
                        emitter.send("执行结束: 达到最大步骤 (" + maxSteps + ")");
                    }
                    // 正常完成
                    emitter.complete();
                } catch (Exception e) {
                    state = AgentState.ERROR;
                    log.error("执行智能体失败", e);
                    try {
                        emitter.send("执行错误: " + e.getMessage());
                        emitter.complete();
                    } catch (Exception ex) {
                        emitter.completeWithError(ex);
                    }
                } finally {
                    // 清理资源
                    this.clean();
                }
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });

        // 设置超时和完成回调
        emitter.onTimeout(() -> {
            this.state = AgentState.ERROR;
            this.clean();
            log.warn("SSE connection timed out");
        });

        emitter.onCompletion(() -> {
            if (this.state == AgentState.RUNNING) {
                this.state = AgentState.FINISHED;
            }
            this.clean();
            log.info("SSE connection completed");
        });

        return emitter;
    }

    public abstract String clean();

    public abstract String step(String userPrompt);
}
